import { ref, reactive, shallowRef } from 'vue'
import * as echarts from 'echarts'
import getInitOption from '../options/CasingPressureOption'
import { getSingleColor } from '../utils/colorUtils'

const chartInstance = shallowRef() // 图表实例
const allCasingPressureData = reactive([]) // 数据
const config = ref({ max: 20, min: 0 }) // 图表配置
const titleFontSize = ref(0) // 图表字体大小
const casingPressureRef = shallowRef()

function registerCasingPressure(casingPressure) {
  casingPressureRef.value = casingPressure
}
function initChart() {
  chartInstance.value = echarts.init(casingPressureRef.value, 'dark')
  chartInstance.value.setOption(getInitOption(config.value))
}
function screenAdapter() {
  titleFontSize.value = (casingPressureRef.value.offsetWidth / 100) * 4
  const progressWidth = titleFontSize.value * 2
  const axisTickLength = titleFontSize.value * 0.5
  const splitLineLength = titleFontSize.value
  const axisLabelDistance = titleFontSize.value
  const detailLineHeight = titleFontSize.value * 2
  const apdaterOption = {
    series: [
      {
        progress: {
          width: progressWidth
        },
        axisLine: {
          lineStyle: {
            width: progressWidth
          }
        },
        axisTick: {
          distance: -(progressWidth + axisTickLength),
          length: axisTickLength
        },
        splitLine: {
          distance: -(progressWidth + splitLineLength),
          length: splitLineLength
        },
        axisLabel: {
          distance: -axisLabelDistance,
          fontSize: titleFontSize.value * 1.5
        },
        detail: {
          lineHeight: detailLineHeight,
          fontSize: titleFontSize.value * 2
        }
      }
    ]
  }
  chartInstance.value.setOption(apdaterOption)
  chartInstance.value.resize()
}
function updateCasingPressure(data, status) {
  const casingPressureData = {
    value: data,
    itemStyle: {
      color: status === 1 ? getSingleColor(7) : getSingleColor(2)
    }
  }
  allCasingPressureData[0] = casingPressureData
  updateCasingPressureChart()
}
function updateCasingPressureChart() {
  const dataOption = {
    series: [
      {
        data: allCasingPressureData
      }
    ]
  }
  chartInstance.value.setOption(dataOption)
}

export const useCasingPressure = () => {
  return {
    registerCasingPressure,
    initChart,
    screenAdapter,
    updateCasingPressure
  }
}
